package com.shujia

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import java.util.Properties

object Demo04KafkaTrans {
  def main(args: Array[String]): Unit = {

    // 1、建立连接
    val properties = new Properties()
    // kafka broker列表
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    // 指定K、V的序列化的类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    // 指定事务id
    properties.setProperty("transactional.id", "trans1")

    val kafkaProducer: KafkaProducer[String, String] = new KafkaProducer[String, String](properties)

    /**
     * 在Kafka中 虽然没有提交事务 数据也会先写入Kafka 但是会打上一个标记为uncommitted
     * 需要配合消费者设置隔离级别：--isolation-level read_committed
     * kafka-console-consumer.sh --bootstrap-server master:9092 --from-beginning --topic trans --isolation-level read_committed
     */
    // 初始化一个事务
    kafkaProducer.initTransactions()
    // 开启一个事务
    kafkaProducer.beginTransaction()
    kafkaProducer.send(new ProducerRecord[String, String]("trans", "transaction1"))
    Thread.sleep(10000)
    kafkaProducer.send(new ProducerRecord[String, String]("trans", "transaction2"))
    kafkaProducer.flush()
    // 提交事务
    kafkaProducer.commitTransaction()

    kafkaProducer.close()

  }

}
